import qbApi from "@rc/apis/qb/index.mjs";
import QuestionShow from "../qb-show/index";

export default {
    name: "question-dialog",
    props: {
        //是否显示弹窗
        visibly: {
            type: Boolean,
            default: false
        },
        resourceProjectList: {
            type: Array,
            default: () => []
        },
        // 默认选中的试题，当点击提交确定时会以此数据为基础和当前弹框内选中的数据进行组合，传递出一个最终的列表[]，单选时接收只包含一个元素的数组
        defaultData: {
            type: Array,
            default: () => []
        },
        searchFomData:{
            type: Object,
            default: () => {}
        }
    },
    components: {
        QuestionShow
    },
    data() {
        return {
            isShow: this.visibly, // 内部的是否显示弹窗
            selectItems: [], // 当前选中的选项列表
            questionForm: { //筛选表单
                projectId: '',
                subjectId: '',
                chapterId: [],
                questioncategoryId: '',
                questionType: '',
            },
            questionList: [],
            questionShowList: [],
            questionTypeList: nlapp.Dictionary.get("rc_questionType"),
            questionCategoryList: [],//项目下试题分类
            projectList: [],//项目列表
            subjectList: [],//科目列表
            loading: false,//加载中
            content: '',//题干内容
            contentKey: 'questionName', //题干搜索字段
            chapterList: [],//章节列表
            chapterProps: {
                multiple: false,
                checkStrictly: true,
                value: "sectionId",
                label: "sectionName",
            },
            isAllCheck: false,//表头全选状态
            headerIndeterminate: false,//表头半选状态
            page: {
                pageIndex: 0,
                pageSize: 10,
                pageCount: 0
            }
        };
    },
    created() {
        // 默认选中值发生变化，之前的选项全部作废
        this.selectItems = JSON.parse(JSON.stringify(this.defaultData));
    },
    watch: {
        // 内部和外部的变量双向绑定
        isShow(val) {
            this.$emit("update:visibly", val);
        },
        visibly(val) {
            this.isShow = val;
        },
        resourceProjectList: {
            handler(val) {
                if (val && val.length) {
                    this.init();
                }
            },
            immediate: true
        },
        defaultData:{
            handler(val){
                if(val){
                    this.selectItems = JSON.parse(JSON.stringify(val));
                    this.updateCheckedState();
                }
            },
        }
    },
    methods: {
        async init() {
            this.projectList = this.resourceProjectList.map((project) => {
                return {
                    projectId: project.projectId,
                    projectName: project.projectName
                };
            });
            if(!this.searchFomData){
                this.subjectList = this.resourceProjectList[0].subjectList;
                this.questionForm.projectId = this.projectList[0].projectId;
                this.questionForm.subjectId = this.subjectList[0].subjectId;
                this.queryTpoSectionTree();//章节
                this.queryQuestionCategoryList();//分类
                this.onSearchClick();//查询

            } else {//根据上次筛选条件查询
                this.loading = true;
                this.questionForm = JSON.parse(JSON.stringify(this.searchFomData.questionForm));
                if(this.questionForm.projectId){
                    const project = this.resourceProjectList.find(project=>project.projectId===this.questionForm.projectId);
                    if(project){
                        this.subjectList = project.subjectList;
                    }
                } else {
                    this.subjectList = this.resourceProjectList[0].subjectList;
                    this.questionForm.projectId = this.projectList[0].projectId;
                    this.questionForm.subjectId = this.subjectList[0].subjectId;
                }
                this.content = this.searchFomData.content;
                this.contentKey = this.searchFomData.contentKey;

                await this.queryTpoSectionTree(); //章节
                await this.queryQuestionCategoryList(); //分类
                setTimeout(()=>{
                    this.onSearchClick();//查询
                },500);

            }


        },

        //回显=更新表格选中状态
        updateCheckedState() {
            this.questionShowList.forEach((question) => {
                if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
                    return;
                } else  if(question.questionstemDetail){
                    let questionId = this.getQuestionId(question);
                    const isCheked = this.selectItems.some((i1) => {
                        let subQuestionId = this.getQuestionId(i1);
                        return questionId === subQuestionId;
                    });
                    question.isChecked = isCheked;
                }else{
                    let questionId = this.getQuestionId(question);
                    const isCheked = this.selectItems.some((i1) => {
                        let subQuestionId = this.getQuestionId(i1);
                        return questionId === subQuestionId;
                    });
                    question.isChecked = isCheked;
                }
            });
            //更新大题的选中状态
            this.questionShowList.forEach((item)=>{
                if (item.questionstemDetail && item.questionstemDetail.questionstemId) {
                    this.updateCombinationChecked(item);
                }
            });
            this.updateIsCheckedAll();
        },
        //表头全选和全不选
        handleCheckAllChange(isAllCheck) {
            this.headerIndeterminate = false;
            this.questionShowList = this.questionShowList.map((question) => {
                question.isChecked = isAllCheck;
                return question;
            });
            this.selectionChange();
        },
        //单行独立题型和大题-选中改变
        rowSelectionChange(question,index) {
            if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
                const subQuestionList = this.questionShowList.filter(item=>item.parentQuestionId===question.questionstemDetail.questionstemId);
                subQuestionList.forEach((subQuestion)=>{
                    subQuestion.isChecked = question.isChecked;
                });
                question.indeterminate = false;
            }
            this.$set(this.questionShowList, index, question);
            this.selectionChange();
            this.updateIsCheckedAll();

        },
        //更新选中的题目信息
        selectionChange() {
            let selectList = [];
            const questionList = this.questionShowList.filter(question=>!(question.questionstemDetail && question.questionstemDetail.questionstemId));
            //选中的试题
            selectList = questionList.filter(question => question.isChecked);
            //检索出当前已缓存并且当前表格中不存在的选项
            const arr = this.selectItems.filter((i1) => {
                let questionId = this.getQuestionId(i1);
                return !questionList.some((i2) => {
                    const i2Id = this.getQuestionId(i2);
                    return questionId === i2Id;
                });
            });
            this.selectItems = [...arr, ...selectList];
        },
        //子级改变
        subSelectionChange(subQuestion) {
            const question = this.questionShowList[subQuestion.parentIndex];
            this.updateCombinationChecked(question);
            this.selectionChange();
            this.updateIsCheckedAll();
        },
        //更新表头选中状态
        updateIsCheckedAll() {
            if (!this.questionShowList.length) {
                this.isAllCheck = false;
                this.headerIndeterminate = false;
                return;
            }
            //是否全选
            const isAllCheck = this.questionShowList.every(question =>question.isChecked);
            //是否有选中
            const hasCheck = this.questionShowList.some(question => question.isChecked);
            this.isAllCheck = isAllCheck;
            this.headerIndeterminate = !isAllCheck && hasCheck;
        },
        //更新复合题型选中状态
        updateCombinationChecked(question) {
            const subQuestionList = this.questionShowList.filter(item=>{
                return item.parentQuestionId===this.getQuestionId(question);
            });
            const qIndex = this.questionShowList.findIndex(item=>{
                return this.getQuestionId(item)===this.getQuestionId(question);
            });
            const isAllCheck = subQuestionList.every(subQuestion => {
                return subQuestion.isChecked;
            });
            //是否有选中
            const hasCheck = subQuestionList.some(subQuestion => {
                return subQuestion.isChecked;
            });
            question.indeterminate = !isAllCheck && hasCheck;
            question.isChecked = isAllCheck;
            this.$set(this.questionShowList, qIndex, question);
        },
        //修改项目
        onChangeProject(projectId) {
            this.subjectList = this.resourceProjectList.find((project) => project.projectId === projectId).subjectList;
            this.questionForm.subjectId = this.subjectList[0].subjectId;
            this.questionForm.questioncategoryId = '';
            this.questionForm.chapterId = [];
            this.queryQuestionCategoryList();
            this.queryTpoSectionTree();
        },
        //修改科目
        onChangeSubject(subjectId) {
            this.questionForm.subjectName = this.subjectList.find((subject) => subject.subjectId === subjectId).subjectName;
        },
        //点击查询按钮
        onSearchClick() {
            this.page = {
                pageIndex: 0,
                pageSize: 10,
                pageCount: 0
            };
            this.getQuestionList();
        },
        // 重置
        onResetClick() {
            this.$refs.questionForm.resetFields();
            this.content = '';//题干内容
            this.contentKey = 'questionName'; //题干搜索字段
            this.init();
        },
        //获取题库章节树
        queryTpoSectionTree() {
           return qbApi.queryTpoSectionTree({
                data: {
                    subjectId: this.questionForm.subjectId,
                    classId: this.questionForm.projectId,
                    sectionShowstatus: 'S',
                    sectionAvlstatus: 'Y',
                },
                success: (res) => {
                    //处理children:[] 为null
                    const  chapterIds = this.questionForm.chapterId;
                    const chapterId = chapterIds.length?chapterIds[chapterIds.length-1]:[];
                    let hasExists = false;
                    let format = function (list) {
                        for (var i = 0; i < list.length; i++) {
                            let item = list[i];
                            if(item.sectionId === chapterId){
                                hasExists = true;
                            }
                            if (item.children.length > 0) {
                                format(item.children);
                            } else {
                                item.children = null;
                            }
                            ;
                        }
                    };
                    format(res.data);
                    //如果换成本地的章节被禁用或删除清空
                    if(!hasExists){
                        this.questionForm.chapterId = [];
                    }
                    this.chapterList = res.data;
                }
            });
        },
        //获取试题分类
        queryQuestionCategoryList() {
            return qbApi.queryQuestionCategoryList({
                data: {
                    classId: this.questionForm.projectId,
                    questioncategoryType: "Y"
                },
                success: (res) => {
                    const questioncategoryId = this.questionForm.questioncategoryId;
                    this.questionCategoryList = res.data;
                    //如果换成本地的分类被删除或禁用 清空
                    const hasExists = res.data.some(category=>category.questioncategoryId===questioncategoryId);
                    if(questioncategoryId && !hasExists){
                        this.questionForm.questioncategoryId = '';
                    }
                }
            });
        },
        getQuestionPage() {
            this.getQuestionList();
        },
        getQuestionList() {
            const { projectId, subjectId, chapterId, questioncategoryId, questionType } = this.questionForm;
            let param = {
                classId:projectId,
                subjectId,
                sectionId: chapterId&& chapterId.length ? chapterId[chapterId.length - 1] : '',
                questioncategoryId,
                questionType,
                questionAvlstatus: 'Y',//已启用
                questionAuditstatus: 'Y',//已审核
                questionRepeattag:'N',//未标记重复
                pageIndex: PageUtil.getStartIndex(this.page),
                pageSize: this.page.pageSize,
                nameCombination: {},
            };
            param.nameCombination[this.contentKey] = this.content;
            this.loading = true;
            qbApi.queryQuestionList({
                data: {
                    ...param
                },
                success: (res) => {
                    let questionShowList = [];
                    this.questionList = res.data;
                    const result = JSON.parse(JSON.stringify(res.data));
                    result.forEach((question, index) => {
                        if (question.questionstemDetail.questionstemId) {
                            question.qIndex = index + 1;
                            questionShowList.push(question);
                            question.questionList.forEach((subQuestion, sIndex) => {
                                subQuestion.qIndex = index + 1 + '-' + (sIndex + 1);
                                subQuestion.parentIndex = index;
                                subQuestion.parentQuestionId = question.questionstemDetail.questionstemId;
                                subQuestion.isSqLast = sIndex === question.questionList.length - 1;//是不是最后一道小题
                                questionShowList.push(subQuestion);
                            });

                        } else {
                            question.qIndex = index + 1;
                            questionShowList.push(question);
                        }
                    });
                    this.questionShowList = questionShowList.map((question) => {
                        question.isChecked = false;
                        return question;
                    });
                    this.page.pageCount = res.count;
                    this.$nextTick(() => {
                        this.updateCheckedState();
                        this.updateIsCheckedAll();
                    });
                },
                complete: (() => {
                    this.loading = false;
                })
            });
        },
        // 控制表格列的边框样式
        tableCellStyle({ row, columnIndex }) {
            //组合题不显示前几列不显示下边框
            const cond1 = row.parentQuestionId && !row.isSqLast;//小题且不是最后一道小题
            const cond2 = row.questionstemDetail && row.questionstemDetail.questionstemId;//是组合题型
            const cond3 = (columnIndex == 0 || columnIndex == 1);//选择框,序号,资源ID
            let result = {};
            if ((cond2 || cond1) && cond3) {
                result['border-bottom'] = 'none';
            }
            result['background'] = 'transparent';
            return result;
        },
        //获取id
        getQuestionId(question) {
            if (question.questionstemDetail && question.questionstemDetail.questionstemId) {//大题
                return question.questionstemDetail.questionstemId;
            }else if (question.questionstemDetail) { // 独立题型
                return question.questionList[0].questionDetail.questionId;
            } else {//大题下小题
                return question.questionDetail.questionId;
            }
        },
        // 点击弹窗确定提交
        onSubmit() {
            this.$emit("submit", this.selectItems);
        },
        //点击取消和关闭按钮，重置已选择的数据
        onClose(){
            this.isShow = false;
            this.selectItems = JSON.parse(JSON.stringify(this.defaultData));
            this.updateCheckedState();
        },
        //获取弹窗内的搜索条件
        api_getSearchFormData(){
            return {
                questionForm:this.questionForm,
                content: this.content,//题干内容
                contentKey: this.contentKey, //题干搜索字段
            };
        }
    },

};
